package com.tg.loginex.helper;

import android.content.Context;
import android.widget.Button;

import androidx.annotation.NonNull;
import androidx.core.util.Consumer;

import com.appbase.custom.constant.CommonConstants;
import com.tange.base.toolkit.PreferenceUtil;
import com.tange.base.toolkit.StringUtils;
import com.tange.core.access.token.Authentication;
import com.tange.core.access.token.Token;
import com.tange.core.backend.service.http.HttpConfigurations;
import com.tange.core.builtin.account.BuiltinAccount;
import com.tange.core.builtin.account.LoginRet;
import com.tange.core.builtin.account.RequireVerificationCodeResp;
import com.tange.core.data.structure.Ret;
import com.tange.module.camera.hub.CameraHub;
import com.tange.module.core.wifi.scan.BizWiFiUtil;
import com.tg.appcommon.android.TGApplicationBase;
import com.tg.appcommon.android.TGLog;
import com.tg.data.http.entity.CountryInfo;
import com.tg.data.http.entity.LoginBean;
import com.widget.TGButton;

import java.util.List;

public class LoginHelper {
    private static final String TAG = "LoginHelper";
    public static final String Global = "Global";
    public static final String PHONE_CODE = "86";
    public static final String CHINA = "中国大陆";
    public static final String START_TYPE = "start_type";
    public static final String START_BIND_INFO = "start_bind_info";
    public static final String TYPE_REGISTER = "register_user";
    public static final String TYPE_BIND = "bind_phone";
    public static final String TYPE_LOGOUT = "start_logout";
    public static final String TYPE_FORGETPWD = "forget_password";
    public static final String TYPE_MODIFY_PWD = "modify_password";
    public static final String LOGIN_MUST_CLEAR_AUTO_LOGIN = "auto_login_clear";
    public static final String LOCK_BELL_SETTING_PASSWORD = "lock_bell_setting_password";
    public static final String LOCK_BELL_FORGET_PASSWORD = "lock_bell_forget_password";
    public static final String LOCK_BELL_ADD_DEVICE_PASSWORD = "lock_bell_add_device_password";
    private String account;
    private String password;
    private boolean autoLogin;
    private boolean autoLoginByWchar;
    private boolean mIsMustClearAutoLoginFlag = false;

    private static boolean loginSuccessCurrentRuntime = false;

    public String getAccount() {
        return account;
    }

    public void setAccount(String account) {
        this.account = account;
    }

    public String getPassword() {
        return password;
    }

    public boolean isAutoLogin() {
        return autoLogin;
    }

    public boolean isAutoLoginByWchar() {
        return autoLoginByWchar;
    }

    public boolean isMustClearAutoLoginFlag() {
        return !mIsMustClearAutoLoginFlag;
    }

    public void setMustClearAutoLoginFlag(boolean mustClearAutoLoginFlag) {
        mIsMustClearAutoLoginFlag = mustClearAutoLoginFlag;
    }

    public void decryptPassword(){
      //  password = TGDESDecrypt.getInstance().decrypt(password);
    }

    private void printUserInfoLog() {
        TGLog.d(TAG, "account = " + account);
        TGLog.d(TAG, "password = " + password);
        TGLog.d(TAG, "autoLogin = " + autoLogin);
        TGLog.d(TAG, "autoLoginByWeChat = " + autoLoginByWchar);
    }

    public void initParam() {
        account = PreferenceUtil.getString(TGApplicationBase.getApplicationContext(), CommonConstants.PRE_USER_NAME);
        password = PreferenceUtil.getString(TGApplicationBase.getApplicationContext(), CommonConstants.PRE_USER_PWD);
        autoLogin = PreferenceUtil.getBoolean(TGApplicationBase.getApplicationContext(), CommonConstants.PRE_AUTO_LOGIN, false);
        autoLoginByWchar = PreferenceUtil.getBoolean(TGApplicationBase.getApplicationContext(), CommonConstants.PRE_AUTO_WECHAT_LOGIN, false);
        printUserInfoLog();
    }


    public static void setPassword(String password){
       // String pwd = TGDESDecrypt.getInstance().encrypt(password);
        if (!StringUtils.isEmpty(password)){
            PreferenceUtil.setString(TGApplicationBase.getBaseContext(), CommonConstants.PRE_USER_PWD, password);
        }
    }

    public static void setButtonEnable(@NonNull Button button, boolean enabled){
        button.setEnabled(enabled);
        button.setAlpha(enabled? 1.f : 0.4f);

    }

    public static void setButtonEnable(@NonNull TGButton button, boolean enabled){
        button.setButtonEnable(enabled);
    }


    public static void registerRequestCountryPhoneCode(Context context, final String account, final String phoneAreaCode, @NonNull final LoginHelper.LoginListener<RequireVerificationCodeResp> listener) {
        BuiltinAccount.INSTANCE.register().requireVerificationCode(context, account, phoneAreaCode, requireVerificationCodeRespResp -> {
            if (requireVerificationCodeRespResp.getSuccess()) {
                if (listener != null) {
                    listener.onSuccess(requireVerificationCodeRespResp.getData());
                }
            } else {
                if (listener != null) {
                    listener.onError(requireVerificationCodeRespResp.getCode(), requireVerificationCodeRespResp.getMessage());
                }
            }
        });
    }

    public static void passwordRequestCountryPhoneCode(Context context, final String account, final String phoneAreaCode, @NonNull final LoginHelper.LoginListener<RequireVerificationCodeResp> listener) {
        BuiltinAccount.INSTANCE.password().requireVerificationCode(context, account, phoneAreaCode, requireVerificationCodeRespResp -> {
            if (requireVerificationCodeRespResp.getSuccess()) {
                if (listener != null) {
                    listener.onSuccess(requireVerificationCodeRespResp.getData());
                }
            } else {
                if (listener != null) {
                    listener.onError(requireVerificationCodeRespResp.getCode(), requireVerificationCodeRespResp.getMessage());
                }
            }
        });
    }


    public void login(final String phoneNum, final String password, @NonNull final LoginListener<LoginBean> loginListener) {
        TGLog.d(TAG, "login");
        BuiltinAccount.INSTANCE.login().login(phoneNum, password, LoginHelper.PHONE_CODE, loginRetResp -> {
            TGLog.d(TAG, "ret = " + loginRetResp.getSuccess());
            if (loginRetResp.getSuccess()){


                LoginRet loginRet = loginRetResp.getData();
                if (loginRet != null){
                    LoginBean content = new LoginBean();
                    long expiresInSeconds = loginRet.getExpiresInSeconds() * 1000 + System.currentTimeMillis();
                    content.setToken(loginRet.getAccessToken());
                    content.setId(String.valueOf(loginRet.getId()));
                    content.setArea_code(LoginHelper.PHONE_CODE);
                    content.setCreated_at(expiresInSeconds);
                    PreferenceUtil.setStringCommit(TGApplicationBase.getApplicationContext(), CommonConstants.LAST_SELECTED_COUNTRY_PHONE_CODE, content.getArea_code());
                    PreferenceUtil.setBoolean(TGApplicationBase.getApplicationContext(), CommonConstants.PRE_PROTOCOL_AGREE,true);
                    loginSuccess(content, phoneNum, password);
                    loginListener.onSuccess(content);
                }

            }else{
                loginListener.onError(loginRetResp.getCode(), loginRetResp.getMessage());
            }
            loginListener.onFinish();
        });
    }

    public static boolean canLoginByToken(){
        String token = PreferenceUtil.getString(TGApplicationBase.getApplicationContext(), CommonConstants.PRE_TOKEN);
        long createAt = PreferenceUtil.getLong(TGApplicationBase.getApplicationContext(), CommonConstants.EXPIRES_IN_SECONDS);

        TGLog.d(TAG, "token = " + token + " createAt = " + createAt + " currentTime = " + System.currentTimeMillis());

        return !StringUtils.isEmpty(token) && createAt > System.currentTimeMillis();
    }

    public static void loginByToken(@NonNull final LoginListener<LoginBean> loginListener) {
        String token = PreferenceUtil.getString(TGApplicationBase.getApplicationContext(), CommonConstants.PRE_TOKEN);
        loginByTokenImpl(token, loginListener);
    }

    public static void loginByTokenImpl(String token, @NonNull final LoginListener<LoginBean> loginListener) {
        if (!StringUtils.isEmpty(token)) {
            Authentication.INSTANCE.configure(token, tokenResp -> {
                if (tokenResp.getSuccess()) {
                    TGLog.i(TAG, "configureToken: success");
                    Token token1 = tokenResp.getData();
                    if (token1 != null) {
                        long expiresInSeconds = token1.getExpiresIn() * 1000 + System.currentTimeMillis();
                        TGLog.d(TAG, "token = " + token + " newToken = " + token1.getToken() + " createAt = " + expiresInSeconds);
                        PreferenceUtil.setString(TGApplicationBase.getApplicationContext(), CommonConstants.PRE_TOKEN, token1.getToken());
                        HttpConfigurations.getInstance().setUserToken(token1.getToken());
                        PreferenceUtil.setLong(TGApplicationBase.getApplicationContext(), CommonConstants.EXPIRES_IN_SECONDS, expiresInSeconds);

                        int userID = token1.getId();
                        if (userID > 0) {
                            PreferenceUtil.setInt(TGApplicationBase.getApplicationContext(), CommonConstants.PRE_USER_ID, userID);
                            HttpConfigurations.getInstance().setUserId(userID);
                            PreferenceUtil.setBoolean(TGApplicationBase.getApplicationContext(), CommonConstants.PRE_AUTO_LOGIN, true);
                            CameraHub.getInstance().setEnableLocalApConnect(false);
                        }
                        loginListener.onSuccess(null);
                    }
                } else {
                    TGLog.i(TAG, "configureToken: failed");
                    loginListener.onError(tokenResp.getCode(), tokenResp.getMessage());
                }
                loginListener.onFinish();
            });
        }
    }

    public static void register(final String account, final String code, final String password, final String phoneAreaCode, final String countryCode, @NonNull final LoginListener<LoginBean> loginListener) {
        BuiltinAccount.INSTANCE.register().create(account, code, password, phoneAreaCode, countryCode, new Consumer<Ret>() {
            @Override
            public void accept(Ret ret) {
                if (ret.getSuccess()){
                    LoginBean content = new LoginBean();
                    content.setArea_code(phoneAreaCode);
                    PreferenceUtil.setStringCommit(TGApplicationBase.getApplicationContext(), CommonConstants.LAST_SELECTED_COUNTRY_PHONE_CODE, content.getArea_code());
                    saveUserInfo(content, account, "");
                    saveLastLoginChannel(CommonConstants.LOGIN_CHANNEL_TANGE);
                    loginListener.onSuccess(content);

                }else{
                    loginListener.onError(ret.getCode(), ret.getMessage());
                }
                loginListener.onFinish();
            }
        });
    }

    public static void reset(final String account, final String code, final String password, final String phoneAreaCode,  @NonNull final LoginListener<LoginBean> loginListener) {
        BuiltinAccount.INSTANCE.password().reset(account, password, code, phoneAreaCode, ret -> {
            if (ret.getSuccess()){
                LoginBean content = new LoginBean();
                content.setArea_code(phoneAreaCode);
                PreferenceUtil.setStringCommit(TGApplicationBase.getApplicationContext(), CommonConstants.LAST_SELECTED_COUNTRY_PHONE_CODE, content.getArea_code());
                saveUserInfo(content, account, "");
                saveLastLoginChannel(CommonConstants.LOGIN_CHANNEL_TANGE);
                loginListener.onSuccess(content);

            }else{
                loginListener.onError(ret.getCode(), ret.getMessage());
            }
            loginListener.onFinish();
        });
    }

    private void loginSuccess(LoginBean content, String phoneNum, String password) {
        BizWiFiUtil.saveNetworkWifi();
        saveUserInfo(content, phoneNum, password);
        saveLastLoginChannel(CommonConstants.LOGIN_CHANNEL_TANGE);
    }

    public synchronized static void saveUserInfo(LoginBean content, String phoneNum, String password) {
        int deviceNum = Integer.parseInt(StringUtils.isEmpty(content.getDevice_num())? "0" : content.getDevice_num());

        if (!StringUtils.isEmpty(content.getId())){
            int userID = Integer.parseInt(content.getId());
            PreferenceUtil.setInt(TGApplicationBase.getApplicationContext(), CommonConstants.PRE_USER_ID, userID);
            HttpConfigurations.getInstance().setUserId(userID);
        }

        PreferenceUtil.setString(TGApplicationBase.getApplicationContext(), CommonConstants.PRE_USER_NAME, phoneNum);
        if (!StringUtils.isEmpty(password)){
            //String pwd = TGDESDecrypt.getInstance().encrypt(password);
            PreferenceUtil.setString(TGApplicationBase.getApplicationContext(), CommonConstants.PRE_USER_PWD, password);
        }

        PreferenceUtil.setString(TGApplicationBase.getApplicationContext(), CommonConstants.PRE_USER_NICK_NAME, content.getNickname());
        PreferenceUtil.setInt(TGApplicationBase.getApplicationContext(), CommonConstants.PRE_DEVICE_NUM, deviceNum);
        PreferenceUtil.setString(TGApplicationBase.getApplicationContext(), CommonConstants.PRE_TOKEN, content.getToken());
        PreferenceUtil.setLong(TGApplicationBase.getApplicationContext(), CommonConstants.EXPIRES_IN_SECONDS, content.getCreated_at());

        TGLog.d(TAG, "saveUserInfo: token = " + content.getToken() + " createAt = " + content.getCreated_at() + "system =" + System.currentTimeMillis());

        HttpConfigurations.getInstance().setUserToken(content.getToken());
        PreferenceUtil.setBoolean(TGApplicationBase.getApplicationContext(), CommonConstants.PRE_AUTO_LOGIN, true);
        CameraHub.getInstance().setEnableLocalApConnect(false);
        TGLog.i(TAG, "[saveUserInfo] updatePushID");

        synchronized (LoginHelper.class) {
            loginSuccessCurrentRuntime = true;
        }
    }

    public synchronized static boolean isLoginSuccessCurrentRuntime() {
        return loginSuccessCurrentRuntime;
    }

    public static void saveLastLoginChannel(String channel) {
        PreferenceUtil.setString(TGApplicationBase.getApplicationContext(), CommonConstants.LAST_LOGIN_CHANNEL, channel);
    }
    public static String getLastLoginChannel() {
       return  PreferenceUtil.getString(TGApplicationBase.getApplicationContext(), CommonConstants.LAST_LOGIN_CHANNEL, "");
    }

    public interface OnCountryPhoneCodeListener {
        void onSuccess(List<CountryInfo> countryInfo);
        void onError(String msg);
    }

    public interface LoginListener<T> {
        void onSuccess(T content);
        void onError(int errorCode, String errorInfo);
        void onFinish();
    }
}
